/* -----------------
* brief
* 1. this is code gen by tools
* 2. mvc code are driver by the model defined with the same filename,
	 for example:
	 there is a Xmodel struct define in xmodel.go file, after the script run (lego model-mvc module_name xmodel)
     it will auto create the code under the module's path
	 m --> xmodel.go
	 v --> view
	 c --> xmodel_ctrl
* 3. you should modify this code if it doesn't satisfy your purpose
*/

package controller

import (
	"encoding/json"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"github.com/valyala/fasthttp"
	"saas_sys_base/common"
	. "saas_sys_base/modules/eshop/models"
	"saas_sys_base/modules/eshop/service"
	product "saas_sys_base/modules/product/service"
	. "saas_sys_base/modules/sysOrders/models"
	. "saas_sys_base/modules/sysOrders/service"
	"time"
)

type OrdersCtrl struct {
	service                 OrdersService
	shopService             service.EShopService
	logisticsCompanyService LogisticsCompanyService
	detailService           OrderDetailService
	specService             product.ProductSpecService
}

func init() {
	vc := new(OrdersCtrl)
	_ctrlList = append(_ctrlList, vc)
}

func (vc *OrdersCtrl) CtrlInfo() string {
	return "OrdersCtrl"
}

func (vc *OrdersCtrl) RoutInit() {
	// 列表页面
	lego.GET("/admin/sysOders/Orders/listpage", vc.ListPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	lego.GET("/admin/sysOders/Orders/listjson", vc.ListJson, lego.LEGO_SESSION_TYPE_ADMIN, false)
	// 编辑页面
	lego.GET("/admin/sysOders/Orders/editpage", vc.GetEditPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	//lego.POST("/admin/Orders/editpage", vc.PostEditPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	// 删除
	//lego.POST("/admin/Orders/del", vc.DelRecode, lego.LEGO_SESSION_TYPE_ADMIN, false)

	//租户管理端接口
	lego.GET("/admin/sysOders/SysOrders/listpage_saas", vc.ListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/alllistjson_saas", vc.AllListJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	lego.GET("/admin/sysOders/SysOrders/unpaylistpage_saas", vc.UnPayListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/unpayistjson_saas", vc.UnPayListJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	lego.GET("/admin/sysOders/SysOrders/paylistpage_saas", vc.PayListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/payistjson_saas", vc.PayistJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	lego.GET("/admin/sysOders/SysOrders/sendedlistpage_saas", vc.SendedListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/sendedistjson_saas", vc.SendedListJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	lego.GET("/admin/sysOders/SysOrders/finishlistpage_saas", vc.FinishListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/finishistjson_saas", vc.FinishListJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	lego.GET("/admin/sysOders/SysOrders/cancellistpage_saas", vc.CancelListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/cancellistjson_saas", vc.CancelListJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	lego.GET("/admin/sysOders/SysOrders/refundlistpage_saas", vc.RefundListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/refundlistjson_saas", vc.RefundListJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	lego.GET("/admin/sysOders/SysOrders/editpage_saas", vc.GetEditPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/deliverypage_saas", vc.GetDelievryPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/sysOders/SysOrders/delivery_saas", vc.Delievry_Saas, lego.LEGO_SESSION_TYPE_ADMIN, true)

	//租户小程序端接口
	lego.APIGET("/api/sysOders/SysOrders/getalllistjson_saas", vc.AllListJson_Saas, true)
	lego.APIGET("/api/sysOders/SysOrders/getpayistjson_saas", vc.PayistJson_Saas, true)
	lego.APIGET("/api/sysOders/SysOrders/getrefundlistjson_saas", vc.RefundListJson_Saas, true)
	lego.APIGET("/api/sysOders/SysOrders/getOrderDetail_saas", vc.GetOrderDetail_Saas, true)
	lego.APIPOST("/api/sysOders/SysOrders/delivery_saas", vc.Delievry_Saas, true)

	//C端接口
	lego.APIGET("/api/sysOders/mall/SysOrders/getalllistjson", vc.ListJson_ForMall, true)
	lego.APIGET("/api/sysOders/mall/SysOrders/getOrderDetail", vc.GetOrderDetail, true)
	lego.APIPOST("/api/sysOders/mall/SysOrders/cancelOrder", vc.CancelOrder, true)



}

/* 列表接口
* params:
  ---
*/
func (vc *OrdersCtrl) ListJson(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		//:saas管理端使用代码，使用时将注释解开 sessionData := common.GetSessionData(&ctxExt)
		//:appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			Keyword string // 关键字查询
			Page    int    `vd:"$>=0"` // 分页
			PSize   int    `vd:"$>0"`  // 分页大小

			OrderField string
			Order      string `vd:"$=='' || $=='asc' || $=='desc'"`
		}
		req := ReqParams{
			Keyword:    string(ctxExt.Peek("keyword")),
			Page:       utils.BytesToInt(ctxExt.Peek("page")),
			PSize:      utils.BytesToInt(ctxExt.Peek("limit")),
			OrderField: string(ctxExt.Peek("order_field")),
			Order:      string(ctxExt.Peek("order")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务查询
		if list, total, err := vc.service.ListOrders(req.Keyword, req.Page, req.PSize, req.OrderField, req.Order); err != nil {
			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *OrdersCtrl) ListPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/list.html", data)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *OrdersCtrl) GetEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		target := vc.service.GetOrdersById(req.Id)
		data["detail"] = target
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/edit.html", data)
	return
}

/* 数据编辑
* params:
  ---
*/
func (vc *OrdersCtrl) PostEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""

	for {
		//:saas管理端使用代码，使用时将注释解开 sessionData := common.GetSessionData(&ctxExt)
		//:appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			//#ModelEditFormDefined#
			Id               int64   `vd:""`
			IfDel            int     `vd:""`
			Cdate            string  `vd:""`
			Udate            string  `vd:""`
			UserId           int64   `vd:""`
			TenantId         int64   `vd:""`
			ShopId           int64   `vd:""`
			UserName         string  `vd:""`
			Mobile           string  `vd:""`
			OrderType        int     `vd:""`
			Province         string  `vd:""`
			City             string  `vd:""`
			Area             string  `vd:""`
			Address          string  `vd:""`
			TradeNo          string  `vd:""`
			ProAmount        int64 `vd:""`
			PayableAmount    int64 `vd:""`
			RealAmount       int64 `vd:""`
			BalanceAmout     int64 `vd:""`
			Postage          int64 `vd:""`
			DiscountFee      int64 `vd:""`
			Remark           string  `vd:""`
			IfPay            int     `vd:""`
			PayTime          string  `vd:""`
			IfCancel         int     `vd:""`
			CancelTime       string  `vd:""`
			IfDelivery       int     `vd:""`
			DeliveryTime     string  `vd:""`
			IfFinish         int     `vd:""`
			IfRefund         int     `vd:""`
			LogisticsId      int64   `vd:""`
			LogisticsCompany string  `vd:""`
			LogisticsNo      string  `vd:""`
		}
		req := ReqParams{
			//#ModelEditFormFiled#
			Id:               utils.BytesToInt64(ctxExt.Peek("id")),
			IfDel:            utils.BytesToInt(ctxExt.Peek("if_del")),
			Cdate:            string(ctxExt.Peek("cdate")),
			Udate:            string(ctxExt.Peek("udate")),
			UserId:           utils.BytesToInt64(ctxExt.Peek("user_id")),
			TenantId:         utils.BytesToInt64(ctxExt.Peek("tenant_id")),
			ShopId:           utils.BytesToInt64(ctxExt.Peek("shop_id")),
			UserName:         string(ctxExt.Peek("user_name")),
			Mobile:           string(ctxExt.Peek("mobile")),
			OrderType:        utils.BytesToInt(ctxExt.Peek("order_type")),
			Province:         string(ctxExt.Peek("province")),
			City:             string(ctxExt.Peek("city")),
			Area:             string(ctxExt.Peek("area")),
			Address:          string(ctxExt.Peek("address")),
			TradeNo:          string(ctxExt.Peek("trade_no")),
			ProAmount:        utils.BytesToInt64(ctxExt.Peek("pro_amount")),
			PayableAmount:    utils.BytesToInt64(ctxExt.Peek("payable_amount")),
			RealAmount:       utils.BytesToInt64(ctxExt.Peek("real_amount")),
			BalanceAmout:     utils.BytesToInt64(ctxExt.Peek("balance_amout")),
			Postage:          utils.BytesToInt64(ctxExt.Peek("postage")),
			DiscountFee:      utils.BytesToInt64(ctxExt.Peek("discount_fee")),
			Remark:           string(ctxExt.Peek("remark")),
			IfPay:            utils.BytesToInt(ctxExt.Peek("if_pay")),
			PayTime:          string(ctxExt.Peek("pay_time")),
			IfCancel:         utils.BytesToInt(ctxExt.Peek("if_cancel")),
			CancelTime:       string(ctxExt.Peek("cancel_time")),
			IfDelivery:       utils.BytesToInt(ctxExt.Peek("if_delivery")),
			DeliveryTime:     string(ctxExt.Peek("delivery_time")),
			IfFinish:         utils.BytesToInt(ctxExt.Peek("if_finish")),
			IfRefund:         utils.BytesToInt(ctxExt.Peek("if_refund")),
			LogisticsId:      utils.BytesToInt64(ctxExt.Peek("logistics_id")),
			LogisticsCompany: string(ctxExt.Peek("logistics_company")),
			LogisticsNo:      string(ctxExt.Peek("logistics_no")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务处理
		recode := vc.service.GetOrdersById(req.Id)
		if recode == nil {
			// 新建
			recode := new(SysOrders)
			//#ModelFiledMapper#'
			recode.Id = req.Id
			recode.IfDel = req.IfDel
			recode.Cdate = req.Cdate
			recode.Udate = req.Udate
			recode.Uid = req.UserId
			recode.TenantId = req.TenantId
			recode.EShopId = req.ShopId
			recode.UserName = req.UserName
			recode.Mobile = req.Mobile
			recode.OrderType = req.OrderType
			recode.Province = req.Province
			recode.City = req.City
			recode.Area = req.Area
			recode.Address = req.Address
			recode.TradeNo = req.TradeNo
			recode.ProAmount = req.ProAmount
			recode.PayableAmount = req.PayableAmount
			recode.RealAmount = req.RealAmount
			recode.BalanceAmout = req.BalanceAmout
			recode.Postage = req.Postage
			recode.DiscountFee = req.DiscountFee
			recode.Remark = req.Remark
			recode.IfPay = req.IfPay
			recode.PayTime = req.PayTime
			recode.IfCancel = req.IfCancel
			recode.CancelTime = req.CancelTime
			recode.IfDelivery = req.IfDelivery
			recode.DeliveryTime = req.DeliveryTime
			recode.IfFinish = req.IfFinish
			recode.IfRefund = req.IfRefund
			recode.LogisticsId = req.LogisticsId
			recode.LogisticsCompany = req.LogisticsCompany
			recode.LogisticsNo = req.LogisticsNo

			if false == vc.service.SaveOrders(recode) {
				code = 100
				msg = "false"
				break
			}
		} else {
			//#ModelFiledMapper#
			recode.Id = req.Id
			recode.IfDel = req.IfDel
			recode.Cdate = req.Cdate
			recode.Udate = req.Udate
			recode.Uid = req.UserId
			recode.TenantId = req.TenantId
			recode.EShopId = req.ShopId
			recode.UserName = req.UserName
			recode.Mobile = req.Mobile
			recode.OrderType = req.OrderType
			recode.Province = req.Province
			recode.City = req.City
			recode.Area = req.Area
			recode.Address = req.Address
			recode.TradeNo = req.TradeNo
			recode.ProAmount = req.ProAmount
			recode.PayableAmount = req.PayableAmount
			recode.RealAmount = req.RealAmount
			recode.BalanceAmout = req.BalanceAmout
			recode.Postage = req.Postage
			recode.DiscountFee = req.DiscountFee
			recode.Remark = req.Remark
			recode.IfPay = req.IfPay
			recode.PayTime = req.PayTime
			recode.IfCancel = req.IfCancel
			recode.CancelTime = req.CancelTime
			recode.IfDelivery = req.IfDelivery
			recode.DeliveryTime = req.DeliveryTime
			recode.IfFinish = req.IfFinish
			recode.IfRefund = req.IfRefund
			recode.LogisticsId = req.LogisticsId
			recode.LogisticsCompany = req.LogisticsCompany
			recode.LogisticsNo = req.LogisticsNo

			if false == vc.service.UpdateOrders(recode) {
				code = 100
				msg = "false"
				break
			}
		}
		break
	}
	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

/* 删除数据记录
* params:
  ---
*/
func (vc *OrdersCtrl) DelRecode(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""
	for {
		// 表单校验
		type ReqParams struct {
			Id int64 `vd:"$>0"` // 记录id
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		// 业务删除
		target := vc.service.GetOrdersById(req.Id)
		if target == nil {
			code = 100
			msg = "记录不存在"
			break
		}

		if false == vc.service.DelOrdersById(target.Id) {
			code = 100
			msg = "操作失败"
			break
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

func (vc *OrdersCtrl) AllListJson_Saas(ctx *fasthttp.RequestCtx) {
	vc.ListJson_Saas(ctx, AllOrder)
}

func (vc *OrdersCtrl) UnPayListJson_Saas(ctx *fasthttp.RequestCtx) {
	vc.ListJson_Saas(ctx, UnPayOrder)
}

func (vc *OrdersCtrl) PayistJson_Saas(ctx *fasthttp.RequestCtx) {
	vc.ListJson_Saas(ctx, PayOrderWaitDelivery)
}

func (vc *OrdersCtrl) SendedListJson_Saas(ctx *fasthttp.RequestCtx) {
	vc.ListJson_Saas(ctx, SendedOrder)
}

func (vc *OrdersCtrl) FinishListJson_Saas(ctx *fasthttp.RequestCtx) {
	vc.ListJson_Saas(ctx, FinishOrder)
}

func (vc *OrdersCtrl) CancelListJson_Saas(ctx *fasthttp.RequestCtx) {
	vc.ListJson_Saas(ctx, CancelOrder)
}

func (vc *OrdersCtrl) RefundListJson_Saas(ctx *fasthttp.RequestCtx) {
	vc.ListJson_Saas(ctx, RefundOrder)
}

//租户管理端 for saas ********
/* 列表接口
* params:
  ---
*/
func (vc *OrdersCtrl) ListJson_Saas(ctx *fasthttp.RequestCtx, orderStatus int) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			OrderCode   string // 关键字查询
			UserName    string //
			Mobile      string //
			BeginTime   string //
			EndTime     string //
			ProductName string //
			OrderType   int
			Page        int `vd:"$>=0"` // 分页
			PSize       int `vd:"$>0"`  // 分页大小

			OrderField string
			Order      string `vd:"$=='' || $=='asc' || $=='desc'"`
		}
		req := ReqParams{
			OrderCode:   string(ctxExt.Peek("order_code")),
			UserName:    string(ctxExt.Peek("user_name")),
			Mobile:      string(ctxExt.Peek("mobile")),
			BeginTime:   string(ctxExt.Peek("begin_time")),
			EndTime:     string(ctxExt.Peek("end_time")),
			ProductName: string(ctxExt.Peek("product_name")),
			OrderType:   utils.BytesToInt(ctxExt.Peek("order_type")),
			Page:        utils.BytesToInt(ctxExt.Peek("page")),
			PSize:       utils.BytesToInt(ctxExt.Peek("limit")),
			OrderField:  string(ctxExt.Peek("order_field")),
			Order:       string(ctxExt.Peek("order")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		shops := vc.shopService.ListByTenandId(appwho.TenantId)
		shopIds := make([]int64, len(shops))

		for i, v := range shops {
			shopIds[i] = v.Id
		}

		// 业务查询
		if list, total, err := vc.service.ListOrdersByWho(appwho, req.OrderCode, req.UserName, req.Mobile, req.BeginTime, req.EndTime, req.ProductName, req.OrderType, shopIds, req.Page, req.PSize, req.OrderField, req.Order, orderStatus); err != nil {
			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *OrdersCtrl) ListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/list_saas.html", data)
	return
}

func (vc *OrdersCtrl) UnPayListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/unpay_list_saas.html", data)
	return
}

func (vc *OrdersCtrl) PayListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/pay_list_saas.html", data)
	return
}

func (vc *OrdersCtrl) SendedListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/sended_list_saas.html", data)
	return
}

func (vc *OrdersCtrl) FinishListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/finish_list_saas.html", data)
	return
}

func (vc *OrdersCtrl) CancelListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/cancel_list_saas.html", data)
	return
}

func (vc *OrdersCtrl) RefundListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/refund_list_saas.html", data)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *OrdersCtrl) GetEditPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		target := vc.service.GetOrdersById(req.Id)

		shops := vc.shopService.ListByTenandId(appwho.TenantId)
		//shopIds := make([]int64,len(shops))

		//for i,v := range  shops{
		//	shopIds[i] = v.Id
		//}

		anyFlag, err := utils.SliceAny(shops, func(elem interface{}) bool {
			v := elem.(*EShop)
			if v.Id == target.EShopId {
				return true
			}
			return false
		})

		if err != nil {
			break
		}
		if !anyFlag {
			break
		}

		data["detail"] = target
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/edit_saas.html", data)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *OrdersCtrl) GetOrderDetail_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}

	response := make(map[string]interface{})
	code := 0
	msg := ""
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = "参数错误"
			break
		}

		target := vc.service.GetOrdersById(req.Id)
		shops := vc.shopService.ListByTenandId(appwho.TenantId)
		//shopIds := make([]int64,len(shops))

		//for i,v := range  shops{
		//	shopIds[i] = v.Id
		//}

		anyFlag, err := utils.SliceAny(shops, func(elem interface{}) bool {
			v := elem.(*EShop)
			if v.Id == target.EShopId {
				return true
			}
			return false
		})

		if err != nil {
			code = 100
			msg = "参数错误"
			break
		}
		if !anyFlag {
			code = 100
			msg = "参数错误"
			break
		}
		target.OrderDetails = vc.detailService.ListByOrderId(req.Id)
		response["data"] = target

		//response["specs"] = vc.specService.ListByProductId(req.Id)
		break
	}
	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *OrdersCtrl) GetDelievryPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		target := vc.service.GetOrdersById(req.Id)

		shops := vc.shopService.ListByTenandId(appwho.TenantId)
		//shopIds := make([]int64,len(shops))

		//for i,v := range  shops{
		//	shopIds[i] = v.Id
		//}

		anyFlag, err := utils.SliceAny(shops, func(elem interface{}) bool {
			v := elem.(*EShop)
			if v.Id == target.EShopId {
				return true
			}
			return false
		})

		if err != nil {
			break
		}
		if !anyFlag {
			break
		}

		data["orderId"] = req.Id
		break
	}
	ctxExt.HTML("sysOrders/view/Orders/delivery_saas.html", data)
	return
}

func (vc *OrdersCtrl) Delievry_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})

	code := 0
	msg := ""
	for {
		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		type DeliveryParam struct {
			Id          int64  `json:"id,string"`
			LogisticsId int64  `json:"logistics_id,string"`
			LogisticsNo string `json:"logistics_no"`
		}

		var deliveryParam DeliveryParam
		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &deliveryParam)

		if err != nil {
			code = 100
			msg = "参数错误"
			break
		}

		target := vc.service.GetOrdersById(deliveryParam.Id)

		shops := vc.shopService.ListByTenandId(appwho.TenantId)
		//shopIds := make([]int64,len(shops))

		//for i,v := range  shops{
		//	shopIds[i] = v.Id
		//}

		anyFlag, err := utils.SliceAny(shops, func(elem interface{}) bool {
			v := elem.(*EShop)
			if v.Id == target.EShopId {
				return true
			}
			return false
		})

		if err != nil {
			code = 100
			msg = "参数错误"
			break
		}
		if !anyFlag {
			code = 100
			msg = "参数错误"
			break
		}

		if target.IfPay == 0 {
			code = 100
			msg = "订单未支付"
			break
		}

		if target.IfDelivery == 1 {
			code = 100
			msg = "订单已支付"
			break
		}

		logisticsCompany := vc.logisticsCompanyService.GetLogisticsCompanyById(deliveryParam.LogisticsId)

		if logisticsCompany == nil {
			code = 100
			msg = "参数错误"
			break
		}

		target.IfDelivery = 1
		target.LogisticsCompany = logisticsCompany.CompanyName
		target.LogisticsId = logisticsCompany.Id
		target.LogisticsNo = deliveryParam.LogisticsNo

		vc.service.UpdateOrders(target)

		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return

}

//c端 ********
/* 列表接口
* params:
  ---
*/
func (vc *OrdersCtrl) ListJson_ForMall(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			OrderCode   string // 关键字查询
			OrderType   int
			OrderStatus int
			Page        int `vd:"$>0"` // 分页
			PSize       int `vd:"$>0"` // 分页大小
			OrderField  string
			Order       string `vd:"$=='' || $=='asc' || $=='desc'"`
		}
		req := ReqParams{
			OrderCode:   string(ctxExt.Peek("order_code")),
			OrderType:   utils.BytesToInt(ctxExt.Peek("order_type")),
			OrderStatus: utils.BytesToInt(ctxExt.Peek("order_status")),
			Page:        utils.BytesToInt(ctxExt.Peek("page")),
			PSize:       utils.BytesToInt(ctxExt.Peek("limit")),
			OrderField:  string(ctxExt.Peek("order_field")),
			Order:       string(ctxExt.Peek("order")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		shop := vc.shopService.GetEShopByTenantId(appwho.TenantId)

		// 业务查询
		if list, total, err := vc.service.ListOrdersByWhoForMall(appwho, req.OrderCode, req.OrderType, shop.Id, req.Page, req.PSize, req.OrderField, req.Order, req.OrderStatus); err != nil {
			lego.LogError(err)
		} else {

			if len(list) > 0 {
				orderIds := make([]int64, len(list))
				for i, v := range list {
					orderIds[i] = v.Id
				}

				var details = vc.detailService.ListByOrderIds(orderIds)
				for _, v := range list {
					orderDetails, _ := utils.SliceFindWhere(details, func(elem interface{}) bool {
						detail := elem.(*SysOrderDetail)
						if v.Id == detail.OrderId && detail.IfDel == 0 {
							return true
						}
						return false
					})

					v.OrderDetails = orderDetails.([]*SysOrderDetail)
				}
			}

			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

func (vc *OrdersCtrl) GetOrderDetail(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}

	response := make(map[string]interface{})
	code := 0
	msg := ""
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = "参数错误"
			break
		}

		target := vc.service.GetOrdersByWho(appwho, req.Id)
		if target == nil {
			code = 100
			msg = "订单不存在"
			break
		}
		shop := vc.shopService.GetEShopByTenantId(appwho.TenantId)
		if target.EShopId != shop.Id {
			code = 100
			msg = "订单不存在"
			break
		}

		target.OrderDetails = vc.detailService.ListByOrderId(req.Id)
		response["data"] = target

		//response["specs"] = vc.specService.ListByProductId(req.Id)
		break
	}
	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

//取消订单
func (vc *OrdersCtrl) CancelOrder(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}

	response := make(map[string]interface{})
	code := 0
	msg := ""
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho

		type ReqParams struct {
			Id int64 `json:"id,string"` // 记录id，为空则新建，否则为编辑
		}
		var req ReqParams
		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &req)

		if err != nil {
			code = 100
			msg = "参数错误"
			break
		}


		target := vc.service.GetOrdersByWho(appwho, req.Id)
		if target == nil {
			code = 100
			msg = "订单不存在"
			break
		}

		shop := vc.shopService.GetEShopByTenantId(appwho.TenantId)
		if target.EShopId != shop.Id {
			code = 100
			msg = "订单不存在"
			break
		}

		if target.IfPay == 1 {
			code = 100
			msg = "订单已支付不能取消"
			break
		}
		target.IfCancel = 1
		target.CancelTime = time.Now().String()
		vc.service.UpdateOrders(target)
		msg = "取消成功"
		//response["specs"] = vc.specService.ListByProductId(req.Id)
		break
	}
	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

